package com.qk.controller;

import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.dto.ClueQueryDTO;
import com.qk.dto.MarkFalseClueDto;
import com.qk.entity.Clue;
import com.qk.enums.ClueEvent;
import com.qk.service.ClueService;
import com.qk.state.service.ClueStateMachineService;
import com.qk.vo.ClueListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 28188
 */
@Slf4j
@RestController
@RequestMapping("/clues")
public class ClueController {
    @Autowired
    private ClueService clueService;
    @Autowired
    private ClueStateMachineService clueStateMachineService;

    @PostMapping
    public Result addClue(@RequestBody Clue clue) {
        log.info("新增线索: {}", clue);
        clueService.addClue(clue);
        return Result.success();
    }

    @GetMapping
    public Result pageClues(ClueQueryDTO clueQueryDTO) {
        log.info("查询线索: {}", clueQueryDTO);
        PageResult<ClueListVO> cluePage = clueService.pageClues(clueQueryDTO);
        return Result.success(cluePage);
    }

    @PutMapping("/assign/{clueId}/{userId}")
    public Result assignClue(@PathVariable String clueId, @PathVariable Integer userId) {
        log.info("分配线索: 线索ID={},用户ID={}", clueId, userId);
        clueStateMachineService.sendEvent(clueId, ClueEvent.ASSIGN, Map.of("userId", userId));
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getClueById(@PathVariable Integer id) {
        log.info("根据ID查询线索: {}", id);
        Clue clue = clueService.getClueById(id);
        return Result.success(clue);
    }

    @PutMapping
    public Result trackClue(@RequestBody Clue clue) {
        log.info("线索跟进: {}", clue);
        clueStateMachineService.sendEvent(String.valueOf(clue.getId()), ClueEvent.START_FOLLOWUP, Map.of("clue", clue));
        return Result.success();
    }

    @PutMapping("/toBusiness/{id}")
    public Result convertToBusiness(@PathVariable String id) {
        log.info("线索转商机: {}", id);
        clueStateMachineService.sendEvent(id, ClueEvent.CONVERT_TO_OPPORTUNITY, null);
        return Result.success();
    }

    @PutMapping("/false/{id}")
    public Result falseClue(@PathVariable String id, @RequestBody MarkFalseClueDto markFalseClueDto) {
        log.info("线索伪线索: {}", id);
        clueStateMachineService.sendEvent(id, ClueEvent.MARK_AS_FAKE, Map.of("markFalseClueDto", markFalseClueDto));
        return Result.success();
    }

    @GetMapping("/pool")
    public Result getCluePool(ClueQueryDTO clueQueryDTO) {
        log.info("查询线索池:{}", clueQueryDTO);
        PageResult<Clue> pool = clueService.pagePool(clueQueryDTO);
        return Result.success(pool);
    }

}
